﻿using StarryEdge.Core.Device;
using StarryEdge.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace StarryEdge.Device.Connections
{
    public class UDPSocket : ICommunication
    {
        private DeviceInfoModel _DeviceInfo;
        public DeviceInfoModel DeviceInfo => _DeviceInfo;
        private byte _suffixIP;
        protected System.Net.Sockets.Socket _socket;

        public UDPSocket(byte suffixIP, DeviceInfoModel model)
        {
            _suffixIP = suffixIP;
            _DeviceInfo = model;
        }

        public void Close()
        {
            if (_socket != null)
            {
                try
                {
                    _socket.Close();
                }
                catch (Exception)
                {
                }
                _socket = null;
            }
        }

        public bool Open()
        {
            try
            {
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                _socket.ReceiveTimeout = 1000;
                _socket.SendTimeout = 1000;
                string[] ip = _DeviceInfo.IPCOM.Split('.');
                _socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse($"{ip[0]}.{ip[1]}.{ip[2]}.{_suffixIP}"), 0));
                _socket.Connect(new IPEndPoint(IPAddress.Parse(_DeviceInfo.IPCOM), _DeviceInfo.Port));
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        public byte[] Receive()
        {
            if (_socket != null)
            {
                byte[] bytes = new byte[1024];
                var count = _socket.Receive(bytes);
                return bytes.Take(count).ToArray();
            }
            return new byte[0];
        }

        public bool Send(byte[] data)
        {
            return _socket.Send(data, SocketFlags.None) == data.Length;
        }
    }
}
